<template>
  <view class="symptoms-container">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="back-btn" @click="goBack">
        <uni-icons type="left" size="20" color="#333"></uni-icons>
      </view>
      <text class="header-title">{{ currentMainTab === 'symptoms' ? '常见病症' : '常用药品' }}</text>
      <view class="placeholder"></view>
    </view>
    
    <!-- 主要标签（病症/药品） -->
    <view class="main-tabs">
      <view 
        class="main-tab-item" 
        :class="{ active: currentMainTab === 'symptoms' }"
        @click="switchMainTab('symptoms')"
      >
        <text>常见病症</text>
      </view>
      <view 
        class="main-tab-item" 
        :class="{ active: currentMainTab === 'drugs' }"
        @click="switchMainTab('drugs')"
      >
        <text>常用药品</text>
      </view>
    </view>
    
    <!-- 左右分栏布局 -->
    <view class="content-layout">
      <!-- 左侧分类列表 -->
      <view class="left-sidebar">
        <view 
          class="category-item" 
          :class="{ active: activeCategory === item.key }"
          v-for="item in currentCategories" 
          :key="item.key"
          @click="switchCategory(item.key)"
        >
          <text>{{ item.name }}</text>
        </view>
      </view>
      
      <!-- 右侧内容区域 -->
      <view class="right-content">
        <!-- 病症列表 -->
        <view class="symptoms-list" v-if="currentMainTab === 'symptoms'">
          <view class="category-section" v-for="category in filteredSymptoms" :key="category.categoryKey">
            <view class="category-header">
              <view class="category-icon">
                <image :src="category.icon" mode="aspectFit"></image>
              </view>
              <text class="category-name">{{ category.categoryName }}</text>
            </view>
            <view class="symptoms-grid">
              <view 
                class="symptom-item" 
                v-for="symptom in category.symptoms" 
                :key="symptom.id"
                @click="viewSymptomDetail(symptom)"
              >
                <text class="symptom-name">{{ symptom.name }}</text>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 药品列表 -->
        <view class="drugs-list" v-if="currentMainTab === 'drugs'">
          <!-- 加载状态 -->
          <view v-if="loading" class="loading-container">
            <text>加载中...</text>
          </view>
          
          <!-- 药品列表内容 -->
          <view v-else>
            <view class="category-section" v-for="category in filteredDrugs" :key="category.categoryKey">
              <view class="category-header">
                <view class="category-icon">
                  <image :src="category.icon" mode="aspectFit"></image>
                </view>
                <text class="category-name">{{ category.categoryName }}</text>
              </view>
              <view class="drugs-grid">
                <view 
                  class="drug-item" 
                  v-for="drug in category.drugs" 
                  :key="drug.id"
                  @click="viewDrugDetail(drug)"
                >
                  <view class="drug-image">
                    <image :src="drug.drugImage" mode="aspectFit"></image>
                  </view>
                  <text class="drug-name">{{ drug.drugName }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getDrugCategoryList, getDrugList } from '@/api/drug'

export default {
  data() {
    return {
      currentMainTab: 'symptoms', // 当前主标签：symptoms 或 drugs
      activeCategory: '',
      loading: false, // 新增loading状态初始化
      symptomsCategories: [], // 清空症状分类数据
      drugsCategories: [],
      symptomsData: [], // 清空症状数据
      drugsData: [] // 初始化药品数据数组
    }
  },
  computed: {
    currentCategories() {
      return this.currentMainTab === 'symptoms' ? this.symptomsCategories : this.drugsCategories
    },
    filteredSymptoms() {
      // 只返回与当前选中分类匹配的数据
      if (!this.symptomsData || this.symptomsData.length === 0 || !this.activeCategory) {
        return []
      }
      return this.symptomsData.filter(item => item.categoryKey === this.activeCategory)
    },
    filteredDrugs() {
      console.log('计算filteredDrugs, activeCategory:', this.activeCategory, 'drugsData:', this.drugsData)
      
      // 只返回与当前选中分类匹配的数据
      if (!this.drugsData || this.drugsData.length === 0) {
        return []
      }
      // 当选择具体分类时，返回匹配的分类数据
      return this.drugsData.filter(item => item.categoryKey === this.activeCategory)
    }
  },
  methods: {
    goBack() {
      uni.navigateBack()
    },
    switchMainTab(tab) {
      // 验证tab参数是否有效
      if (tab !== 'symptoms' && tab !== 'drugs') {
        console.error('无效的标签:', tab)
        this.$modal.msg('无效的标签选择')
        return
      }
      
      this.currentMainTab = tab
      this.activeCategory = '' // 切换主标签时重置分类
      
      if (tab === 'drugs') {
        this.loadDrugCategories()
      } else {
        // 对于症状标签，如果有分类数据，默认选中第一个
        if (this.symptomsCategories.length > 0 && !this.activeCategory) {
          this.activeCategory = this.symptomsCategories[0].key
        }
      }
    },
    switchCategory(categoryKey) {
      console.log('切换分类:', categoryKey, '当前标签:', this.currentMainTab)
      this.activeCategory = categoryKey
      
      // 如果是药品标签，则根据选中的分类加载药品数据
      if (this.currentMainTab === 'drugs') {
        // 验证分类键是否有效
        if (!categoryKey) {
          console.error('无效的分类键:', categoryKey)
          this.$modal.msg('无效的分类选择')
          return
        }
        
        // 加载该分类的药品数据
        console.log('加载分类药品数据:', categoryKey)
        this.loadDrugsByCategory(categoryKey)
      }
    },
    viewSymptomDetail(symptom) {
      this.$modal.msg(`查看病症详情：${symptom.name}`)
    },
    viewDrugDetail(drug) {
      // 添加日志记录以便诊断问题
      console.log('点击药品，准备导航到详情页:', drug)
      
      // 检查drug对象和id是否存在
      if (!drug || !drug.id) {
        console.error('药品对象或ID不存在:', drug)
        this.$modal.msg('无法查看药品详情：药品信息无效')
        return
      }
      
      try {
        // 导航到药品详情页面并传递药品ID
        console.log('执行导航，URL:', `/pages/drug/index?id=${drug.id}`)
        const result = uni.navigateTo({
          url: `/pages/drug/index?id=${drug.id}`
        })
        console.log('导航结果:', result)
      } catch (error) {
        console.error('导航失败:', error)
        this.$modal.msg('导航到药品详情页失败')
      }
    },
    loadDrugCategories() {
      console.log('开始加载药品分类')
      getDrugCategoryList().then(response => {
        console.log('药品分类响应:', response)
        
        // 检查响应是否存在且code为200
        if (!response || response.code !== 200) {
          console.error('获取药品分类失败:', response ? response.msg : '响应为空')
          this.$modal.msg('获取药品分类失败，请重试')
          return
        }
        
        // 检查response.data是否存在
        if (!response.data) {
          console.error('药品分类数据为空')
          this.$modal.msg('获取药品分类失败，数据为空')
          return
        }
        
        // 使用正确的字段名 categoryName
        const categories = response.data.map(item => ({
          key: item.id,
          name: item.categoryName
        }))
        console.log('处理后的分类数据:', categories)
        this.drugsCategories = categories
        
        // 如果有分类数据，默认选中第一个分类
        if (categories.length > 0 && !this.activeCategory) {
          this.activeCategory = categories[0].key
        }
        
        // 当加载分类后，如果当前已有选中分类，则加载对应分类的药品
        if (this.activeCategory) {
          const categoryKeys = categories.map(c => c.key)
          console.log('当前选中分类:', this.activeCategory, '可用分类keys:', categoryKeys)
          if (categoryKeys.includes(this.activeCategory)) {
            this.loadDrugsByCategory(this.activeCategory)
          } else {
            console.log('分类不存在，重置为第一个分类')
            this.activeCategory = categories[0].key
            this.loadDrugsByCategory(this.activeCategory)
          }
        } else {
          // 默认加载第一个分类的药品数据
          if (categories.length > 0) {
            this.activeCategory = categories[0].key
            this.loadDrugsByCategory(this.activeCategory)
          }
        }
      }).catch(error => {
        console.error('获取药品分类失败:', error)
        this.$modal.msg('获取药品分类失败，请检查网络连接')
      })
    },
    


    loadDrugsByCategory(categoryId) {
      // 显示加载状态
      this.loading = true
      
      // 调用API获取药品列表
      getDrugList(categoryId).then(response => {
        this.loading = false
        
        // 检查响应是否存在且code为200
      if (response && response.code === 200) {
        // 获取当前分类的名称
        let categoryName = '未知分类'
        const currentCategory = this.drugsCategories.find(cat => cat.key === categoryId)
        if (currentCategory) {
          categoryName = currentCategory.name
        } else {
          // 如果在drugsCategories中找不到，尝试在drugsData中查找
          const existingCategory = this.drugsData.find(cat => cat.categoryKey === categoryId)
          if (existingCategory) {
            categoryName = existingCategory.categoryName
          }
        }
        
        // 构建药品数据结构，使用正确的response.rows路径
        const drugsForCategory = {
          categoryKey: categoryId,
          categoryName: categoryName,
          icon: 'https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=1111111111,1111111111&fm=26&gp=0.jpg',
          drugs: response.rows || []
        }
          
          // 检查当前分类是否已存在于drugsData中
          const index = this.drugsData.findIndex(item => item.categoryKey === categoryId)
          if (index >= 0) {
            // 更新现有分类的数据
            this.drugsData.splice(index, 1, drugsForCategory)
          } else {
            // 添加新的分类数据
            this.drugsData.push(drugsForCategory)
          }
        } else {
          console.error('获取药品列表失败:', response ? response.msg : '响应为空')
          this.$modal.msg('获取药品列表失败，请重试')
        }
      }).catch(error => {
        this.loading = false
        console.error('获取药品列表失败:', error)
        this.$modal.msg('获取药品列表失败，请检查网络连接')
      }).finally(() => {
        // 确保loading状态被正确关闭
        this.loading = false
      })
    },
  },
  onLoad(options) {
    // 检查options参数是否存在
    if (options) {
        // 检查URL参数，如果有tab参数则切换到对应标签
        if (options.tab === 'drugs') {
          this.currentMainTab = 'drugs'
          this.loadDrugCategories()
        }
      }
  }
}
</script>

<style lang="scss" scoped>
.symptoms-container {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
  
  .back-btn {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .header-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
  }
  
  .placeholder {
    width: 60rpx;
  }
}

// 主要标签样式
.main-tabs {
  display: flex;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
  
  .main-tab-item {
    flex: 1;
    padding: 30rpx 0;
    text-align: center;
    position: relative;
    
    &.active {
      color: #667eea;
      
      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 60rpx;
        height: 4rpx;
        background-color: #667eea;
        border-radius: 2rpx;
      }
    }
    
    text {
      font-size: 30rpx;
      font-weight: 500;
    }
  }
}

// 左右分栏布局
.content-layout {
  display: flex;
  flex: 1;
  height: calc(100vh - 200rpx); // 减去头部和标签的高度
}

// 左侧分类栏
.left-sidebar {
  width: 200rpx;
  background-color: #f8f8f8;
  border-right: 1rpx solid #eee;
  
  .category-item {
    padding: 30rpx 20rpx;
    text-align: center;
    border-bottom: 1rpx solid #eee;
    
    &.active {
      background-color: #fff;
      color: #667eea;
      position: relative;
      
      &::after {
        content: '';
        position: absolute;
        right: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 4rpx;
        height: 40rpx;
        background-color: #667eea;
        border-radius: 2rpx;
      }
    }
    
    text {
      font-size: 28rpx;
    }
  }
}

// 右侧内容区域
.right-content {
  flex: 1;
  overflow-y: auto;
  padding: 20rpx;
}

.symptoms-list, .drugs-list {
  // 移除原有的padding，因为已在right-content中设置
}

.category-section {
  margin-bottom: 40rpx;
  
  .category-header {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;
    
    .category-icon {
      width: 60rpx;
      height: 60rpx;
      margin-right: 20rpx;
      
      image {
        width: 100%;
        height: 100%;
        border-radius: 8rpx;
      }
    }
    
    .category-name {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }
  }
}

.symptoms-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  
  .symptom-item {
    width: calc(50% - 10rpx);
    padding: 20rpx;
    background-color: #fff;
    border-radius: 12rpx;
    text-align: center;
    
    .symptom-name {
      font-size: 28rpx;
      color: #333;
    }
  }
}

.drugs-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  
  .drug-item {
    width: calc(33.33% - 14rpx);
    padding: 20rpx;
    background-color: #fff;
    border-radius: 12rpx;
    text-align: center;
    
    .drug-image {
      width: 80rpx;
      height: 80rpx;
      margin: 0 auto 10rpx;
      
      image {
        width: 100%;
        height: 100%;
        border-radius: 8rpx;
      }
    }
    
    .drug-name {
      font-size: 24rpx;
      color: #333;
      line-height: 1.4;
    }
  }
}

// 加载状态样式
.loading-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 300rpx;
  color: #999;
  font-size: 28rpx;
}
</style>